using System;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using umbraco;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.member;
using umbraco.cms.businesslogic.propertytype;
using umbraco.interfaces;

namespace umbracoMemberControls
{
    /// <summary>
    ///		Summary description for tilmelding.
    /// </summary>
    public partial class umbRegister : UserControl
    {
        private ArrayList _dataFields = new ArrayList();
        private string _memberTypeAlias = "";
        private string _memberGroups = "";
        private int _redirectId = 0;
        private string _errorUserNameTaken = "- The username is in use, please pick another";
        private string _errorEmailInUse = "- The e-mail is in use, please use another or use the forgot password form";

        private string _showPropertiesFromTabs;

        public string ShowPropertiesFromTabs
        {
            get { return _showPropertiesFromTabs; }
            set { _showPropertiesFromTabs = value.ToLower(); }
        }

        private bool _useClientValidation = false;

        public bool UseClientScriptValidation
        {
            get { return _useClientValidation = false; }
            set { _useClientValidation = value; }
        }

        private bool _useCookiesForAuthentication = false;

        public bool UseCookiesForAuthentication
        {
            get { return _useCookiesForAuthentication; }
            set { _useCookiesForAuthentication = value; }
        }

        public string MemberTypeAlias
        {
            set { _memberTypeAlias = value; }
        }

        public string MemberGroups
        {
            set { _memberGroups = value; }
        }

        public int RedirectToPageOnSucces
        {
            set { _redirectId = value; }
        }

        public string ErrorUserNameTaken
        {
            set { _errorUserNameTaken = value; }
        }

        public string ErrorEmailInUse
        {
            set { _errorEmailInUse = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (!UseClientScriptValidation)
                {
                    RequiredFieldValidator1.EnableClientScript = false;
                    RequiredFieldValidator2.EnableClientScript = false;
                    RequiredFieldValidator4.EnableClientScript = false;
                    RequiredFieldValidator5.EnableClientScript = false;
                    CompareValidator1.EnableClientScript = false;
                }
            }
            
        }

        #region Web Form Designer generated code

        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);

            // loop through custom controls
            if (ShowPropertiesFromTabs != "")
            {
                MemberType mt = MemberType.GetByAlias(_memberTypeAlias);
                foreach (ContentType.TabI tab in mt.getVirtualTabs)
                {
                    if ((", " + ShowPropertiesFromTabs + ",").Contains(", " + tab.Caption.ToLower() + ","))
                    {
                        foreach (PropertyType pt in tab.PropertyTypes)
                        {
                            if (mt.MemberCanEdit(pt))
                            {
                                IDataType propertyControl = pt.GetEditControl("", IsPostBack);
                                propertyControl.DataEditor.Editor.ID = pt.Alias;
                                umbraco.interfaces.IData df = pt.DataTypeDefinition.DataType.Data;
                                ((Control) propertyControl.DataEditor.Editor).ID = pt.Alias;
                                _dataFields.Add(propertyControl);

                                // add controls
                                System.Web.UI.WebControls.Label label = new Label();
                                label.AssociatedControlID = pt.Alias;
                                label.Text = pt.Name;
                                customFields.Controls.Add(new LiteralControl("<p>"));
                                customFields.Controls.Add(label);
                                customFields.Controls.Add((Control) propertyControl.DataEditor.Editor);

                                // Validation
                                if (pt.Mandatory)
                                {
                                    try
                                    {
                                        System.Web.UI.WebControls.RequiredFieldValidator rq = new RequiredFieldValidator();
                                        rq.ControlToValidate = propertyControl.DataEditor.Editor.ID;
                                        rq.EnableClientScript = UseClientScriptValidation;
                                        rq.CssClass = "umbracoAutoFormAlert";
                                        rq.Display = System.Web.UI.WebControls.ValidatorDisplay.Dynamic;
                                        string[] errorVars = { pt.Name, "" };
                                        rq.ErrorMessage = "<br/>" + umbraco.ui.Text("errorHandling", "errorMandatoryWithoutTab", errorVars, null);
                                        customFields.Controls.Add(rq);
                                    }
                                    catch (Exception valE)
                                    {
                                        System.Web.HttpContext.Current.Trace.Warn("contentControl", "EditorControl (" + propertyControl.DataTypeName + ") does not support validation", valE);
                                    }
                                }

                                // RegExp Validation
                                if (pt.ValidationRegExp != "")
                                {
                                    try
                                    {
                                        System.Web.UI.WebControls.RegularExpressionValidator rv = new RegularExpressionValidator();
                                        rv.ControlToValidate = propertyControl.DataEditor.Editor.ID;
                                        rv.ValidationExpression = pt.ValidationRegExp;
                                        rv.EnableClientScript = UseClientScriptValidation;
                                        rv.CssClass = "umbracoAutoFormAlert";
                                        rv.Display = System.Web.UI.WebControls.ValidatorDisplay.Dynamic;
                                        string[] errorVars = { pt.Name, "" };
                                        rv.ErrorMessage = "<br/>" + umbraco.ui.Text("errorHandling", "errorRegExpWithoutTab", errorVars, null);
                                        customFields.Controls.Add(rv);
                                    }
                                    catch (Exception valE)
                                    {
                                        System.Web.HttpContext.Current.Trace.Warn("contentControl", "EditorControl (" + propertyControl.DataTypeName + ") does not support validation", valE);
                                    }

                                }

                                if (pt.Description != "")
                                {
                                    customFields.Controls.Add(new LiteralControl("<br/><span class=\"umbracoAutoFormRowDescription\">" + pt.Description + "<br/></span>"));
                                }


                                customFields.Controls.Add(new LiteralControl("</p>"));
                            }
                        }
                    }
                }

                if (!IsPostBack && _dataFields.Count > 0) {
                    customFields.Controls.AddAt(0, new LiteralControl("<fieldset id=\"customFields\">"));
                    customFields.Controls.Add(new LiteralControl("</fieldset>"));
                }
            }
        }

        /// <summary>
        ///		Required method for Designer support - do not modify
        ///		the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
        }

        #endregion

        protected void ButtonSignup_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                bool hasErrors = false;
                additionalErrors.Text = "";

                // Check if username is taken

                try
                {
                    if (Member.GetMemberFromLoginName(username.Text.Trim()) != null)
                    {
                        hasErrors = true;
                        additionalErrors.Text = _errorUserNameTaken + "<br/>";
                    }
                }
                catch
                {
                }
                try
                {
                    if (Member.GetMemberFromEmail(email.Text) != null)
                    {
                        hasErrors = true;
                        additionalErrors.Text += _errorEmailInUse + "<br/>";
                    }
                }
                catch
                {
                }

                if (!hasErrors)
                {
                    Member m =
                        Member.MakeNew(name.Text, email.Text, MemberType.GetByAlias(_memberTypeAlias), new User(0));
                    m.LoginName = username.Text.Trim();
                    m.Password = password.Text;

                    // Save properties
                    foreach (IDataType df in _dataFields)
                    {
                        df.Data.PropertyId = m.getProperty(df.DataEditor.Editor.ID).Id;
                        df.DataEditor.Save();
                    }

                    // Add groups
                    if (_memberGroups.Trim() != "")
                    {
                        foreach (string mg in _memberGroups.Split(",".ToCharArray()))
                        {
                            MemberGroup Group = MemberGroup.GetByName(mg);
                            if (Group != null)
                                m.AddGroup(Group.Id);
                        }
                    }

                    if (UseCookiesForAuthentication)
                        Member.AddMemberToCache(m);
                    else
                        Member.AddMemberToCache(m, true, new TimeSpan(0, 0, 0));
                    
                    Response.Redirect(library.NiceUrl(_redirectId), true);
                }
                else
                {
                    additionalErrors.Text = "<p class=\"umbSignupError\">" + additionalErrors.Text + "</p>";
                }
            }
        }
    }
}
